package leetcode;

import leetcode.util.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * Created by tiang on 2018/9/7.
 */
public class PrintTree {
    /**
     * 通过迭代的方式输出树的后序遍历
     * @param root 根节点
     * @return 后序遍历列表
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        // 存储未遍历的节点
        Stack<TreeNode> stack = new Stack<>();
        // 存放最终结果
        Stack<Integer> res = new Stack<>();
        stack.push(root);
        while(!stack.empty()) {
            TreeNode pointer = stack.pop();
            while (pointer != null) {
                // 向右侧遍历，将左子节点加入栈中
                res.push(pointer.val);
                if (pointer.left != null)
                    stack.push(pointer.left);
                pointer = pointer.right;
            }
        }
        List<Integer> result = new ArrayList<>();
        while(!res.empty())
            result.add(res.pop());
        return result;
    }
}
